using System;
using System.Linq;
using Greg.XmlEditor.Presentation.Presenters;

namespace Greg.XmlEditor.Presentation.Commands.Concrete
{
	public class SaveAllCommand : CommandBase
	{
		private readonly MasterPresenter presenter;
		private readonly ICommand saveCommand;
		private readonly IInteractionManager interaction;

		public SaveAllCommand(MasterPresenter presenter, ICommand saveCommand, IInteractionManager interaction)
		{
			this.presenter = presenter;
			this.saveCommand = saveCommand;
			this.interaction = interaction;
		}

		/// <summary>
		/// Refreshes the command state.
		/// </summary>
		public override void Refresh()
		{
			this.IsEnabled = (this.presenter.Documents.Count > 0); //&& this.Documents.All(d => d.IsPersistent);
		}

		/// <summary>
		/// Executes the command logics.
		/// </summary>
		public override void Invoke()
		{
			try
			{
				this.presenter.Documents.ToList().ForEach(d =>
				                                          	{
				                                          		this.presenter.CurrentDocument = d;
				                                          		this.saveCommand.Invoke();
				                                          	});
			}
			catch (Exception ex)
			{
				this.interaction.ShowError(ex.Message);
			}
		}
	}
}